<?php

declare (strict_types=1);

namespace App\Model;

use Hyperf\DbConnection\Model\Model;

/**
 */
class DiscountVideoRank extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'discount_video_rank';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [];
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [];

    /**
     * 更新每周特惠视频时长
     * @param int $userId
     * @param int $callTime
     * @return bool
     */
    public static function updateCallTime(int $userId, int $callTime)
    {
        // 小于10秒不统计
        if ($callTime < 10) {
            return false;
        }

        $model = self::getInfo($userId);
        if (empty($model)) {
            $model = new self();

            $year = (int)date("o");
            $week = (int)date('W');

            $model->user_id = $userId;
            $model->year = $year;
            $model->week = $week;
            $model->call_time = 0;
            $model->call_num = 0;
            $model->created_at = date('Y-m-d H:i:s');
        }

        $model->updated_at = date('Y-m-d H:i:s');
        $model->call_time += ceil($callTime / 60);
        $model->call_num += 1;

        DiscountVideoUsers::addVideoInfo($userId, ceil($callTime / 60));

        return $model->save();
    }

    /**
     * 获取前100名
     * @param int $userId
     * @return array
     */
    public static function getRankInfo(int $userId)
    {
        $year = (int)date("o");
        $week = (int)date('W');

        $where = [
            'week' => $week,
            'year' => $year,
        ];

        $model = self::leftJoin('user_profile', 'user_profile.user_id', '=', 'discount_video_rank.user_id')
            ->orderBy('call_time', 'desc')->where($where)
            ->select(['discount_video_rank.user_id', 'nick_name', 'discount_video_rank.call_time', 'avatar'])
            ->limit(100)->get()->toArray();

        return $model;
    }

    /**
     * 获取周视频数据
     * @param int $userId
     * @return \Hyperf\Database\Model\Builder|\Hyperf\Database\Model\Model|object|null
     */
    public static function getInfo(int $userId)
    {
        $year = (int)date("o");
        $week = (int)date('W');

        $where = [
            'week' => $week,
            'year' => $year,
            'user_id' => $userId
        ];

        return self::where($where)->first();
    }

    public static function quitDiscountVideo($userId)
    {
        return self::where(['user_id' => $userId])->delete();
    }
}
